package com.example.oauth2.config;

import com.example.oauth2.domain.JiuBoDouDaoAuthenticationProvider;
import com.example.oauth2.domain.JiuBoDouUserPasswordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @ClassName JiuBoDouWebConfig
 * @Description
 * @Author huyingliang
 * @Date 2024-03-05 9:35
 */
@Configuration
public class JiuBoDouWebConfig extends WebSecurityConfigurerAdapter {

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/oauth2/**").permitAll()
                .anyRequest().authenticated();
        http.cors();/*允许跨域*/
    }

    @Autowired
    UserDetailsService jiuBoDouUserDetailService;

    @Override
    protected void configure(AuthenticationManagerBuilder builder) {

        JiuBoDouDaoAuthenticationProvider provider = new JiuBoDouDaoAuthenticationProvider();
        provider.setPasswordEncoder(new BCryptPasswordEncoder());
        provider.setUserDetailsService(jiuBoDouUserDetailService);
        provider.setUserDetailsPasswordService(new JiuBoDouUserPasswordService());
        provider.setHideUserNotFoundExceptions(false);
        builder.authenticationProvider(provider);
    }
}
